# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
from datetime import datetime
from models import *
from django.db import connection, transaction
import settings


def branch_list(request, product):
    product = Product.objects.get(id=product)
    object_list = Branch.objects.filter(product = product)
    return render_to_response('report/branch_list.html', {'object_list': object_list, 'product': product})

def query_all_latest(product, branch):
    sqlcommand = """
select * from report_component join report_toolconfig
join report_tool on (report_toolconfig.tool_id = report_tool.id and report_tool.category_id = report_component.category_id)
join report_product on report_component.product_id = report_product.id
left outer join report_rankdata as r on (r.component_id = report_component.id and r.tool_config_id = report_toolconfig.id)
left outer join report_target on (r.component_id = report_target.component_id and report_target.branch_id = report_toolconfig.branch_id)
where report_component.product_id = 1 and report_toolconfig.branch_id = 1  and (create_time =
(
  select max(create_time)
  from report_rankdata
  where report_rankdata.component_id = r.component_id and report_rankdata.tool_config_id = r.tool_config_id
)) or create_time is null;
"""
    cursor = connection.cursor()
    cursor.execute(sqlcommand, [product.id, branch.id])
    return cursor.fetchall()

def component_list(request, product, branch):
    branch = Branch.objects.get(id=branch)
    product = Product.objects.get(id=product)

    def get_category(category):
        components = Component.objects.filter(product = product, category = category)
        tool_configs = ToolConfig.objects.filter(branch = branch, tool__category = category)
        
        def get_component(component):
            target = Target.objects.get(component = component, branch = branch)
            total_rank = 0.0
            data_line = []
            for tool_config in tool_configs:
                if tool_config.tool.category == component.category:
                    data = RankData.objects.filter(component = component, tool_config = tool_config).order_by('-create_time')
                    data_line.append(data[0].html if len(data) > 0 else 'n/a')
                    rank = data[0].rank if len(data) > 0 else 0.0
                    total_rank += rank * tool_config.weight
                
            return {'name':component.name, 'data':data_line, 'total_rank':total_rank, 'target_rank':target.target_rank, 'rank_ok': (total_rank >= target.target_rank)}
        
        component_list = [get_component(component) for component in components]
        return {'name': category.name, 'tool_config_list': tool_configs, 'component_list': component_list }

    category_list = [get_category(category) for category in Category.objects.all()]
    return render_to_response('report/component_list.html', {'product': product, 'branch': branch, 'category_list': category_list})


def get_latest(tool_config, component):
    data = RankData.objects.filter(component = component, tool_config = tool_config).order_by('-create_time')
    return data[0] if len(data) > 0 else None


def store_data(tool_config, component, raw, rank, html, old_data):
    raw = repr(raw)
    now = datetime.now()
    if old_data and old_data.raw == raw:
        old_data.refresh_time = now
        old_data.save()
        return 'SAME'
    else:
        new_data = RankData(component = component, tool_config = tool_config, raw = raw, rank = rank, html = html, create_time = now, refresh_time = now)
        new_data.save()
        return 'CHANGED'


def update(request):
    response = ''
    for tool_config in ToolConfig.objects.all():
        response += 'updating %s:\n' %tool_config
        try:
            plugin_config = {}
            plugin = {}
            exec tool_config.config_code.replace('\r\n', '\n') in plugin_config
            exec tool_config.tool.code.replace('\r\n', '\n') in plugin
            config = plugin_config['get_config'](tool_config.branch)
            components = Component.objects.filter(product=tool_config.branch.product, category = tool_config.tool.category)
            for component in components:
                response += '%s, ' % component.name
                old_data = get_latest(tool_config, component)
                old_raw = eval(old_data.raw) if old_data else None
                old_rank = old_data.rank if old_data else 0.0
                raw = plugin['get_raw'](config, component)
                rank = plugin['get_rank'](config, component, raw)
                html= plugin['get_html'](config, component, raw, old_raw, rank, old_rank)
                result = store_data(tool_config, component, raw, rank, html, old_data)
                response += '%s\n' % result
        except Exception as e:
            response += '%s\n' % e
            #if settings.DEBUG:
            #    raise
        
    return HttpResponse(response + "All Completed", mimetype="text/plain")
